//定义全局变量 读取api 接口地址
import base64 from '@/common/base64.js';
import crypot from '@/common/crypot.js';
const apiPath = '/';

function getDES(value) { //加密
	var key = '97498121231284655fsafasa'; //密钥
	var iv = 'kfao5417';
	var key = crypot.enc.Utf8.parse(key);
	var iv = crypot.enc.Utf8.parse(iv);
	var encrypted = crypot.DES.encrypt(value, key, {
		iv: iv, //向量  偏移量
		mode: crypot.mode.CBC, //加密模式
		padding: crypot.pad.Pkcs7 //填充模式 补位
	});
	var encrypted = encrypted.toString();
	return base64.Base64.encode(encrypted);
}

// 文章数据处理
function artHandle(list,type) {
	let artBgs = ['http://files.zhizhuedu.cn/202103111014.png', 'http://files.zhizhuedu.cn/202103111015.png',
	'http://files.zhizhuedu.cn/202103111016.png', 'http://files.zhizhuedu.cn/202103111017.png'];
	let typeVal = '';
	if(type) {
		typeVal = type;
	}
	list.forEach((item, index) => {
		if (item.title) {
			item.title = item.title.replace(/amp;/g, '').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/[, ]/g, '');
		}
		if (item.content) {
			item.content = item.content.replace(/amp;/g, '').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
			item.content = item.content.replace(/><video>/g,'"autoplay="true" loop="true" show-center-play-btn="true" show-play-btn="false"></video>'
			).replace(/src=/g, 'style="max-width:100%;" src=');
			if (typeVal == '') {
				item.content = item.content.split('<img')[0];
				item.content = item.content.split('<video')[0];
				item.content = item.content.split('[#')[0];
			}
		}
		if (item.img_url) {
			var arr = item.img_url.split('.'); //分割图片
			var suffix = arr[arr.length-1]; //获取图片后缀名
			// 判断封面图片类型，若封面图片不是图片类型则设为空
			if(suffix != 'png' && suffix != 'jpg' && suffix != 'jpeg' && suffix != 'gif') {
				item.img_url = '';
			}
		}
		if (!item.img_url && ((item.article_video == 1 && item.videoList && item.videoList.length > 0) || item.article_video == 2)) {
			let num = Math.round(Math.random() * 3); //随机生成背景图索引
			item['videoImage_url'] = artBgs[num];
		}
	})
	return list;
}

// 年级显示
function getgradeName(id) {
	var gradeName = '';
	switch (id) {
		case 1:
			gradeName = '一年级';
			break;
		case 2:
			gradeName = '二年级';
			break;
		case 3:
			gradeName = '三年级';
			break;
		case 4:
			gradeName = '四年级';
			break;
		case 5:
			gradeName = '五年级';
			break;
		case 6:
			gradeName = '六年级';
			break;
		case 7:
			gradeName = '七年级';
			break;
		case 8:
			gradeName = '八年级';
			break;
		case 9:
			gradeName = '九年级';
			break;
		case 10:
			gradeName = '高一';
			break;
		case 11:
			gradeName = '高二';
			break;
		case 12:
			gradeName = '高三';
			break;
		default:
			gradeName = '全部';
			break;
	}
	return gradeName;
}

// 年级数组显示
function getStage(type) {
	var Stage = [
		[{
			'grade': 1,
			'grade_name': '一年级'
		}, {
			'grade': 2,
			'grade_name': '二年级'
		}, {
			'grade': 3,
			'grade_name': '三年级'
		}, {
			'grade': 4,
			'grade_name': '四年级'
		}, {
			'grade': 5,
			'grade_name': '五年级'
		}, {
			'grade': 6,
			'grade_name': '六年级'
		}],
		[{
			'grade': 7,
			'grade_name': '七年级'
		}, {
			'grade': 8,
			'grade_name': '八年级'
		}, {
			'grade': 9,
			'grade_name': '九年级'
		}],
		[{
			'grade': 10,
			'grade_name': '高一'
		}, {
			'grade': 11,
			'grade_name': '高二'
		}, {
			'grade': 12,
			'grade_name': '高三'
		}]
	]
	if (type == 999) { //不分阶段为一组，带名称和ID
		var arr = [];
		for (var i = 0; i < Stage.length; i++) {
			for (var j = 0; j < Stage[i].length; j++) {
				arr.push(Stage[i][j]);
			}
		}
		return arr
	} else if (type == 998) { //根据阶段分三组，带名称和ID，插入全部
		for (var i = 0; i < Stage.length; i++) {
			Stage[i].unshift({
				'grade': '',
				'grade_name': '全部年级'
			})
		}
		return Stage
	} else if (type == 997) { //不分阶段为一组，带名称
		var arr = [];
		for (var i = 0; i < Stage.length; i++) {
			for (var j = 0; j < Stage[i].length; j++) {
				arr.push(Stage[i][j].grade_name);
			}
		}
		return arr
	} else if (type == 996) { //根据阶段分三组，带名称
		var arr = [];
		for (var i = 0; i < Stage.length; i++) {
			arr[i] = [];
			for (var j = 0; j < Stage[i].length; j++) {
				arr[i].push(Stage[i][j].grade_name);
			}
		}
		return arr
	} else if (type == 995) { //根据阶段分三组，带ID
		var arr = [];
		for (var i = 0; i < Stage.length; i++) {
			arr[i] = [];
			for (var j = 0; j < Stage[i].length; j++) {
				arr[i].push(Stage[i][j].grade);
			}
		}
		return arr
	} else { //根据阶段分三组，带名称和ID
		return Stage
	}
}

// 题型显示
function getTypeName(type) {
	var typeNmae = '';
	switch (type) {
		case 1:
			typeNmae = '单选题';
			break;
		case 2:
			typeNmae = '多选题';
			break;
		case 3:
			typeNmae = '判断题';
			break;
		case 4:
			typeNmae = '填空题';
			break;
		case 5:
			typeNmae = '问答题';
			break;
		case 6:
			typeNmae = '定值填空题';
			break;
		case 7:
			typeNmae = '阅读材料题';
			break;
		case 8:
			typeNmae = '材料问答填空';
			break;
		case 9:
			typeNmae = '病句修改';
			break;
		case 10:
			typeNmae = '简答题';
			break;
		case 11:
			typeNmae = '画图题';
			break;
		case 12:
			typeNmae = '选考题';
			break;
		case 13:
			typeNmae = '综合题';
			break;
		case 14:
			typeNmae = '选择填空';
			break;
		case 15:
			typeNmae = '材料填空题';
			break;
		case 16:
			typeNmae = '短文改错';
			break;
		case 17:
			typeNmae = '材料题';
			break;
		case 18:
			typeNmae = '材料填空';
			break;
		case 19:
			typeNmae = '听写题';
			break;
		case 20:
			typeNmae = '解答题';
			break;
		case 21:
			typeNmae = '句型转换题';
			break;
		case 22:
			typeNmae = '完形填空';
			break;
		case 23:
			typeNmae = '语法填空';
			break;
		case 24:
			typeNmae = '单词拼写';
			break;
		case 25:
			typeNmae = '词形转换';
			break;
		case 26:
			typeNmae = '默写';
			break;
		case 27:
			typeNmae = '还原句子';
			break;
		case 28:
			typeNmae = '补全对话';
			break;
		case 29:
			typeNmae = '填空题';
			break;
		case 30:
			typeNmae = '解答题';
			break;
		case 31:
			typeNmae = '判断改错';
			break;
		case 32:
			typeNmae = '名著导读';
			break;
		case 33:
			typeNmae = '听写题';
			break;
		case 34:
			typeNmae = '作文题';
			break;
		case 35:
			typeNmae = '实验题';
			break;
		case 36:
			typeNmae = '语言表达';
			break;
		case 37:
			typeNmae = '翻译';
			break;
		case 38:
			typeNmae = '推断题';
			break;
		case 39:
			typeNmae = '辨析题';
			break;
		case 40:
			typeNmae = '探究题';
			break;
		case 41:
			typeNmae = '分析说明题';
			break;
		case 42:
			typeNmae = '连线题';
			break;
		case 43:
			typeNmae = '口语题';
			break;
		case 44:
			typeNmae = '计算题';
			break;
		case 45:
			typeNmae = '口算题';
			break;
		case 46:
			typeNmae = '选词填空';
			break;
		case 47:
			typeNmae = '复合题';
			break;
		case 48:
			typeNmae = '诗歌鉴赏';
			break;
		case 49:
			typeNmae = '文言文阅读';
			break;
		case 50:
			typeNmae = '现代文阅读';
			break;
		case 51:
			typeNmae = '阅读题';
			break;
		case 52:
			typeNmae = '综合性学习';
			break;
		case 53:
			typeNmae = '阅读理解';
			break;
		case 54:
			typeNmae = '任务阅读';
			break;
		case 55:
			typeNmae = '综合题';
			break;
		default:
			typeNmae = '全部题型';
			break;
	}
	return typeNmae;
}

// 类型显示
function getKindName(type) {
	/* 根据test_type显示对应的名称 */
	if (type == 'zice') {
		return '自评'
	} else if (type == 'mokao') {
		return '模考'
	} else if (type == 'yuekao') {
		return '月考'
	} else if (type == 'qizhong') {
		return '期中'
	} else if (type == 'qimo') {
		return '期末'
	} else if (type == 'zhenti') {
		return '真题'
	} else if (type == 'gufen') {
		return '估分'
	} else if (type == 'yati') {
		return '押题'
	} else if (type == 'wenzong') {
		return '文综'
	} else if (type == 'lizong') {
		return '理综'
	} else if (type == 'danyuan') {
		return '单元'
	} else if (type == 'zhice') {
		return '智测'
	} else if (type == 'kaochang') {
		return '考场'
	}
}

// 格式化文章类型
function getArtType(type) {
	/* 根据test_type显示对应的名称 */
	if (type == 1) {
		return '理想'
	} else if (type == 2) {
		return '学习规划'
	} else if (type == 3) {
		return '职业规划'
	} else if (type == 4) {
		return '成绩'
	} else if (type == 5) {
		return '评语'
	} else if (type == 6) {
		return '奖状'
	} else if (type == 7) {
		return '兴趣'
	} else if (type == 8) {
		return '特长'
	} else if (type == 9) {
		return '家规'
	} else if (type == 10) {
		return '祖训'
	} else if (type == 11) {
		return '家务'
	} else if (type == 12) {
		return '兴家'
	} else if (type == 13) {
		return '祖传'
	}
}

// 科目图标显示
function getIcon(name) {
	var icon = '';
	switch (name) {
		case '语文':
			icon = 'iconyuwen';
			break;
		case '数学':
			icon = 'iconshuxue';
			break;
		case '英语':
			icon = 'iconyingyu';
			break;
		case '物理':
			icon = 'iconwuli';
			break;
		case '化学':
			icon = 'iconhuaxueyongpin';
			break;
		case '生物':
			icon = 'iconshengwu';
			break;
		case '地理':
			icon = 'icondili';
			break;
		case '历史':
			icon = 'iconlishi';
			break;
		case '政治':
			icon = 'iconzhengzhi';
			break;
		case '思想品德':
			icon = 'iconzhengzhi';
			break;
		default:
			icon = 'iconyuwen';
			break;
	}
	return icon;
}

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}

var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function(milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function(dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function(number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function(str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	},
	// 不包括年月
	duration: function(date1, date2, type) {
		if (!(date2 instanceof Date)) {
			date2 = new Date();
		}
		var duration = Math.abs(date1 - date2);
		type = type === 'M' ? 0 : type;
		// default MM
		switch (type) {
			// 日
			case 'd':
				return ~~(duration / 86400000)
				// 时
			case 'H':
				return ~~(duration / 3600000)
				// 秒
			case 's':
				return ~~(duration / 1000)
			default:
				// 分
				return ~~(duration / 60000)
		}
	}
};
/**
 * @param {Object} content
 * @param {Object} class_style
 * @param {Object} base_style北京接口图片解析
 */
function Replace_str(content, class_style, base_style) {
	var text = content.replace(/<\/?((?!img).)*?\/?>/g, "");
	text = text.replace(/src="http/g, class_style + ' src="http');
	text = text.replace(/src="data:/g, base_style + ' src="data:');
	text = text.replace(/src=\\"/g, class_style + ' src="');
	text = text.replace(/src="\/ueditor/g, class_style + ' src="http://lexiao.app.limeiti.cn/ueditor');
	text = text.replace(/.png\\/g, '.png');
	text = text.replace(/.jpg\\/g, '.jpg');
	text = text.replace(/\[|]/g, '')
	text = text.replace(/&nbsp;/gi, '');
	return text;
};
/**
 * @param {Object} stamp珠海接口图片解析
 */
function Replace_img(content, class_style, base_style) {
	var text = content.replace(/<\/?((?!img).)*?\/?>/g, "");
	text = text.replace(/src="/g, class_style + ' src="http://192.168.2.115:81/question/');
	text = text.replace(/\[|]/g, '')
	text = text.replace(/&nbsp;/gi, '');
	return text;
}

/* 时间戳(仅显示年月日、时分秒) */
function getFormatTime(stamp) {
	let stampLength = stamp.toString().length
	let tstamp
	if (stampLength == 10) {
		tstamp = new Date(stamp * 1000)
	} else if (stampLength == 13) {
		tstamp = new Date(stamp)
	} else {
		return
	}

	let year = tstamp.getFullYear(tstamp)
	let month = tstamp.getMonth(tstamp) + 1
	let day = tstamp.getDate(tstamp)
	let hour = tstamp.getHours(tstamp)
	let minute = tstamp.getMinutes(tstamp)
	let second = tstamp.getSeconds(tstamp)
	if (month < 10) {
		month = '0' + month
	}
	if (day < 10) {
		day = '0' + day
	}
	if (hour < 10) {
		hour = '0' + hour
	}
	if (minute < 10) {
		minute = '0' + minute
	}
	if (second < 10) {
		second = '0' + second
	}

	return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}

/* 时间戳(仅显示年月日、时分)（个位前加零) */
function getBriefTime(stime) {
	let stimeLength = stime.toString().length
	let tstime
	if (stimeLength == 10) {
		tstime = new Date(stime * 1000)
	} else if (stimeLength == 13) {
		tstime = new Date(stime)
	} else {
		return
	}

	let year = tstime.getFullYear(tstime)
	let month = tstime.getMonth(tstime) + 1
	let day = tstime.getDate(tstime)
	let hour = tstime.getHours(tstime)
	let minute = tstime.getMinutes(tstime)
	if (month < 10) {
		month = '0' + month
	}
	if (day < 10) {
		day = '0' + day
	}
	if (hour < 10) {
		hour = '0' + hour
	}
	if (minute < 10) {
		minute = '0' + minute
	}
	return `${year}-${month}-${day} ${hour}:${minute}`
}

/* 时间戳(仅显示年月日)（个位前加零) */
function getLeftTime(stime) {
	let stimeLength = stime.toString().length
	let tstime
	if (stimeLength == 10) {
		tstime = new Date(stime * 1000)
	} else if (stimeLength == 13) {
		tstime = new Date(stime)
	} else {
		return
	}

	let year = tstime.getFullYear(tstime)
	let month = tstime.getMonth(tstime) + 1
	let day = tstime.getDate(tstime)
	let hour = tstime.getHours(tstime)
	let minute = tstime.getMinutes(tstime)
	if (month < 10) {
		month = '0' + month
	}
	if (day < 10) {
		day = '0' + day
	}
	return `${year}-${month}-${day}`
}

/* 时间戳(显示月日、时分（个位前加零) */
function getAllTime(stime) {
	let stimeLength = stime.toString().length
	let tstime
	if (stimeLength == 10) {
		tstime = new Date(stime * 1000)
	} else if (stimeLength == 13) {
		tstime = new Date(stime)
	} else {
		return
	}

	let month = tstime.getMonth(tstime) + 1
	let day = tstime.getDate(tstime)
	let hour = tstime.getHours(tstime)
	let minute = tstime.getMinutes(tstime)

	if (day < 10) {
		day = '0' + day
	}
	if (hour < 10) {
		hour = '0' + hour
	}
	if (minute < 10) {
		minute = '0' + minute
	}

	return `${month}-${day}　${hour}:${minute}`
}

/* 时间戳(仅显示月日)（个位前加零) */
function getnewTime(stime) {
	let stimeLength = stime.toString().length
	let tstime
	if (stimeLength == 10) {
		tstime = new Date(stime * 1000)
	} else if (stimeLength == 13) {
		tstime = new Date(stime)
	} else {
		return
	}

	let year = tstime.getFullYear(tstime)
	let month = tstime.getMonth(tstime) + 1
	let day = tstime.getDate(tstime)
	let hour = tstime.getHours(tstime)
	let minute = tstime.getMinutes(tstime)
	if (month < 10) {
		month = '0' + month
	}
	if (day < 10) {
		day = '0' + day
	}
	return `${month}-${day}`
}

/* 时间戳(仅显示月日) */
function getTodayTime(stime) {
	let stimeLength = stime.toString().length
	let tstime
	if (stimeLength == 10) {
		tstime = new Date(stime * 1000)
	} else if (stimeLength == 13) {
		tstime = new Date(stime)
	} else {
		return
	}

	let month = tstime.getMonth(tstime) + 1
	let day = tstime.getDate(tstime)
	return `${month}.${day}`
}

function checkUpdate(callback) {
	plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
		uni.request({
			url: 'http://ftp.zhizhuedu.cn/h5/zzjy_2.0/version/s/student.json',
			success: function(result) {
				var data = result.data.data;

				var currentVersions = widgetInfo.version.split('.');
				var resultVersions = data.version.split('.');

				var wgt_current_version = currentVersions[1] + '.' + currentVersions[2];
				var wgt_result_version = resultVersions[1] + '.' + resultVersions[2];

				if (currentVersions[0] < resultVersions[0]) {
					// uni.showToast({
					// 	title:currentVersions[0] +'==='+ resultVersions[0]
					// })
					callback(true)
				} else if (parseFloat(wgt_current_version, 2) < parseFloat(wgt_result_version, 2)) {
					// uni.showToast({
					// 	title:currentVersions[2] +'==='+ resultVersions[2]
					// })
					callback(true)
				} else {
					// uni.showToast({
					// 	title:currentVersions[2] +'==='+ resultVersions[2]
					// })
					callback(false)
				}
			}
		})
	})
}

function getToken() {
	var Token = uni.getStorageSync('_token');
	if (!Token) {
		uni.request({
			url: 'http://lexiao.limeiti.cn/index.php?act=api&cmd=app-api-op-token', //仅为示例，并非真实接口地址。
			data: {
				data: JSON.stringify({
					apiid: 7000,
					apisecret: 'lexiao'
				})
			},
			method: 'POST',
			header: {
				'Content-Type': 'application/json;charset=UTF-8',
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			success: res => {
				//空令牌设置到缓存中
				uni.setStorageSync('_token', res.data.data.token);
			}
		});
	}
}

function getAnalysis(data, interest_lists_log = "interest_lists_log") {
	var len = data.length;
	var letter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'];
	data.forEach((item, index) => {
		item.question_type_name = getTypeName(item.question_typeid);
		item.answer = "";
		item.myanswer = "";
		if ((item.is_one_choice == 2 && item.question_typeid != 3) || item.is_many_choice == 2) {
			item.answer_list.forEach((aitem, aindex) => {
				var str = 'A';
				var code = str.charCodeAt();
				var str2 = String.fromCharCode(code + aindex);
				aitem.text = str2;
				aitem.lettertext = letter[aindex];
				if (aitem.is_answer == 1) {
					item.answer += letter[aindex];
				}
				if (item[interest_lists_log][0]) {
					item.is_answer = item[interest_lists_log][0].is_answer;
					if (typeof(item[interest_lists_log][0]['question_answer_id']) == "object") {
						item[interest_lists_log][0]['question_answer_id'].forEach((laitem, laindex) => {
							if (aitem.question_answer_id == laitem) {
								item.myanswer += letter[aindex];
							}
						})
					}
				}
			})
		} else {
			if (item.answer_list) {
				item.answer_list.forEach((aitem, aindex) => {
					if (aitem.is_answer == 1) {
						if (item.answer) {
							item.answer += '......' + aitem.answer;
						} else {
							item.answer += aitem.answer;
						}
					}
				})
			}
			if (item[interest_lists_log].length > 0) {
				if (item[interest_lists_log][0].answer_img_list) {
					item.answer_img_list = item[interest_lists_log][0].answer_img_list.split(',');
				}
				item.voice_url = item[interest_lists_log][0].voice_url;
				item.postil = item[interest_lists_log][0].postil;
				item.is_answer = item[interest_lists_log][0].is_answer;
				if (item[interest_lists_log][0].user_text_answer.length > 0) {
					item[interest_lists_log][0].user_text_answer.forEach((val, key) => {
						if (item.myanswer) { //答案数组已经有缓存的数据
							if (val) { //这个空答题了
								item.myanswer += '......' + val;
							} else {
								item.myanswer += '......' + '没答题';
							}
						} else { //答案数组已经还没有缓存的数据
							if (val) {
								item.myanswer += val;
							} else {
								item.myanswer += '没答题';
							}
						}
					})
				}
			}
			if (item.question_typeid == 11) {
				item.question_photo = item.question_photo;
			}
		}
	});
	return data;
}

/**
 * 
 * latex_reques(obj,key)
 * @param {Object} 试题列表
 * @param {String} json对象 key 名
 * */
function latex_reques(obj, key) {
	obj.forEach((item, index) => {
		if (!item[key]) return false
		/**
		 * 规则
		 * */
		var matchReg1 = /\$\$.*?\$\$/g; //规则1 公式以$$开头和结尾
		var matchReg2 = /\$.*?\$/g; //规则2 公式以$ 开头和结尾
		var matchReg3 = /\$\S.*?\$/g; //规则3  此规则比较特殊，存在此规则是当存在两个公式连贯出现时 会组合成 以$$ 开头 以$ 结尾的特殊组合
		var latex_match_reg =
			/<img class="latex" src="http:\/\/latex.codecogs.com\/svg.latex\?">.*?<img class="latex" src="http:\/\/latex.codecogs.com\/svg.latex\?">/g;

		/**
		 * 试题标题 latex 公式解析
		 * */
		var replaceTitle = item[key].replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;lt;/g, '<')
			.replace(
				/&amp;gt;/g, '>').replace(/src=/g,
				'style="max-width:100%;" src=');; //首选将公式中的 < > 于号转义回来,图片设最大宽度
		var title = replaceTitle.match(matchReg2);
		//第一次过滤 $$   $$
		if (title != null) {
			title.forEach((v, i) => {
				var imgUrl = encodeURI("http://latex.codecogs.com/svg.latex?" + v.replace(/\$/g, ''));
				replaceTitle = replaceTitle.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(v,
					'<img class="latex" src="' +
					imgUrl + '">');
			});
			item[key] = replaceTitle;
		}

		//北京试题库图片和现系统试题库 图片转换
		if (item.qid == null) {
			item[key] = replaceTitle.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"')
				.replace(
					/&amp;nbsp;/g,
					"  ").replace(/&amp;#39;/g, "'").replace(/src="http:\/\/lexiao.limeiti.cn\/Public\/qvnet/g,
					'class="zh_img" src="http://ftp.zhizhuedu.cn/Public/qvnet').replace(/src="\/ueditor/g,
					'class="zh_img" src="http://ftp.zhizhuedu.cn/Public/qvnet/ueditor').replace(/&amp;gt;/g,
					'>')
		} else {
			item[key] = replaceTitle.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"')
				.replace(
					/&amp;nbsp;/g,
					"  ").replace(/&amp;#39;/g, "'").replace(/src=\\http:\/\/gallery.fbcontent.cn\/latex?/g,
					'class="latex" src="http://gallery.fbcontent.cn/latex').replace(
					/src="http:\/\/caizi.st.netos.cn\/ueditor/g,
					'class="bj_img_w" src="http://wechat.zhizhuedu.cn/ueditor').replace(
					/src="http:\/\/lexiao.limeiti.cn\/ueditor/g,
					'class="bj_img_w" src="http://wechat.zhizhuedu.cn/ueditor').replace(/src="\/ueditor/g,
					'class="bj_img_w" src="http://wechat.zhizhuedu.cn/ueditor').replace(/src="data:image/g,
					'class="base_img_title" src="data:image').replace(/&amp;gt;/g, '>');
		}

		//第二次过滤
		var $_str = item[key].match(matchReg1);
		var replaceTitle_str = item[key];
		if ($_str != null) {
			$_str.forEach((v, i) => {
				var imgUrl = encodeURI("http://latex.codecogs.com/svg.latex?" + v.replace(/\$/g, ''));
				replaceTitle_str = replaceTitle_str.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(
					v,
					'<img class="latex" src="' + imgUrl + '">');
			});
			item[key] = replaceTitle_str;
		}

		//第三次过滤
		var latex_img = item[key].match(latex_match_reg);
		var latex_title = item[key];
		if (latex_img != null) {
			latex_img.forEach((v, i) => {
				var imgUrl = encodeURI("http://latex.codecogs.com/svg.latex?" + v.replace(
					/<img class="latex" src="http:\/\/latex.codecogs.com\/svg.latex\?">/g, ''));
				latex_title = latex_title.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(v,
					'<img class="latex" src="' +
					imgUrl + '">');
			});
			item[key] = latex_title;
		}

		return item[key].replace(/<(?!img).*?>/g, '');
	})
}


/**
 * 答案选项
 * latex_answer(obj,key)
 * @param {Object} 试题列表
 * @param {String} json对象 key 名
 * */
function latex_answer(obj, key) {
	obj.forEach((item, index) => {
		if (!item[key]) return false
		/**
		 * 规则
		 * */
		var matchReg1 = /\$\$.*?\$\$/g; //规则1 公式以$$开头和结尾
		var matchReg2 = /\$.*?\$/g; //规则2 公式以$ 开头和结尾
		var matchReg3 = /\$\S.*?\$/g; //规则3  此规则比较特殊，存在此规则是当存在两个公式连贯出现时 会组合成 以$$ 开头 以$ 结尾的特殊组合
		var latex_match_reg =
			/<img class="latex" src="http:\/\/latex.codecogs.com\/svg.latex\?">.*?<img class="latex" src="http:\/\/latex.codecogs.com\/svg.latex\?">/g;
		/**
		 * 答案选项 latex 公式解析
		 * */
		var answerAry = item[key];
		answerAry.forEach((v, i) => {
			var replaceAnswerList = v.answer.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(
				/&quot;/g, '"').replace(
				/&amp;lt;/g, '<').replace(/&amp;gt;/g, '>').replace(/src=/g,
				'style="max-width:100%;" src=');
			var analysis = replaceAnswerList.match(matchReg1);

			if (analysis != null) {
				analysis.forEach((vl, k) => {
					var imgUrl = encodeURI("http://latex.codecogs.com/svg.latex?" + vl.replace(
						/\$/g, ''));
					replaceAnswerList = replaceAnswerList.replace(vl,
						'<img class="latex" src="' + imgUrl + '">');
				});
				v.answer = replaceAnswerList
			}
			//北京试题库图片和现系统试题库 图片转换
			if (item.qid == null) {
				v.answer = replaceAnswerList.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(
					/&amp;nbsp;/g, "  ").replace(
					/&amp;#39;/g, "'").replace(/src="\/ueditor/g,
					'src="http://ftp.zhizhuedu.cn/Public/qvnet/ueditor').replace(
					/&amp;gt;/g, '>');
			} else {
				v.answer = replaceAnswerList.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(
						/&amp;nbsp;/g, "  ").replace(
						/&amp;#39;/g, "'").replace(/src="http:\/\/caizi.st.netos.cn\/ueditor/g,
						'class="bj_img_w" src="http://wechat.zhizhuedu.cn/ueditor').replace(
						/src=\\http:\/\/gallery.fbcontent.cn\/latex?/g,
						'class="latex" src="http://gallery.fbcontent.cn/latex').replace(
						/src=\\\/ueditor/g, 'class="bj_img" src="http://wechat.zhizhuedu.cn/ueditor')
					.replace(new RegExp("\\.png",
							"g"),
						'.png"').replace(/src=\\http:\/\/caizi.st.netos.cn/g,
						'class="latex" src="http://wechat.zhizhuedu.cn').replace(
						/src=\\data:image/g, 'class="base_img" src="data:image').replace(/\\\//g, '"')
					.replace(/&amp;gt;/g, '>');
			}
			//第二次过滤
			var $_str = v.answer.match(matchReg2);
			var replaceTitle_str = v.answer;
			if ($_str != null) {
				$_str.forEach((v, i) => {
					var imgUrl = encodeURI("http://latex.codecogs.com/svg.latex?" + v.replace(
						/\$/g, ''));
					replaceTitle_str = replaceTitle_str.replace(/&lt;/g, '<').replace(/&gt;/g,
						'>').replace(v,
						'<img class="latex" src="' + imgUrl + '">');
				});
				v.answer = replaceTitle_str.replace(/<(?!img).*?>/g, '');
			}

			//第三次过滤
			var latex_img = v.answer.match(latex_match_reg);
			var latex_title = v.answer;

			if (latex_img != null) {
				latex_img.forEach((v, i) => {
					var imgUrl = encodeURI("http://latex.codecogs.com/svg.latex?" + v.replace(
						/<img class="latex" src="http:\/\/latex.codecogs.com\/svg.latex\?">/g,
						''));
					latex_title = latex_title.replace(/&lt;/g, '<').replace(/&gt;/g, '>')
						.replace(v, '<img class="latex" src="' +
							imgUrl + '">');
				});
				v.answer = latex_title.replace(/<(?!img).*?>/g, '');
			}
			v.answer = v.answer.replace(/<(?!img).*?>/g, '')

		});

		return answerAry;
	})
}

/* 
 * 字符串工具，过长省略
 * @param	[fn] hander 允许自定义处理
 * @author	Asan 
 * */
String.prototype.ellipsis = function(limit, hander) {
	// 计算真实长度
	var i = this.length,
		len = 0,
		str = [],
		size;
	while (i--) {
		size = (this.charCodeAt(i) <= 128) ? 1 : 2;
		str.unshift(size)
		len += size
	}
	if (len > limit) {
		size = 0;
		i = str.findIndex(function(sz) {
			return (size += sz) > limit
		})
	}
	return ~i ? 'function' === typeof hander ? hander.call(this, i) : this.slice(0, i - 1) + '...' : this
}
/**
 * 修改阅读数据
 * @param {int} class_id班级id
 * @param {int} user_id用户id
 * @param {int} user_type用户类型
 */
function Clearnum(class_id, user_id, user_type) {
	var classkey = 'class' + class_id; //班级聊天记录key
	var typekey = class_id + 'usr_type' + user_type; //好友类型key
	var userkey = class_id + 'usr_type' + user_type + 'user' + user_id; //好友key

	var Num = '';

	var user_data = uni.getStorageSync(userkey);
	Num = user_data.num;
	user_data.num = 0;
	uni.setStorageSync(userkey, user_data);

	var class_data = uni.getStorageSync(classkey);
	class_data.num = class_data.num - Num;
	uni.setStorageSync(classkey, class_data);

	var type_data = uni.getStorageSync(typekey);
	type_data.num = type_data.num - Num;
	uni.setStorageSync(typekey, type_data);

	// uni.getStorage({
	// 	key: userkey,
	// 	success: function(res) {
	// 		var data = res.data;
	// 		Num = data.num;
	// 		data.num = 0;
	// 		uni.setStorage({
	// 			key: userkey,
	// 			data: data
	// 		})
	// 	}
	// })
	// uni.getStorage({
	// 	key: classkey,
	// 	success: function(res) {
	// 		var data = res.data;
	// 		data.num = data.num - Num;
	// 		uni.setStorage({
	// 			key: classkey,
	// 			data: data
	// 		})
	// 	}
	// })
	// uni.getStorage({
	// 	key: typekey,
	// 	success: function(res) {
	// 		var data = res.data;
	// 		data.num = data.num - Num;
	// 		uni.setStorage({
	// 			key: typekey,
	// 			data: data
	// 		})
	// 	}
	// })
}

/**
 * 保存聊天信息
 * @param {array} msgdata 
 * @param {boole} is_add true=阅读数增加 fales=阅读数不增加
 * @param {boole} is_send true=发送消息 fales=接收消息
 * @param {int} accept_user_id 接收人的id
 * @param {int} accept_user_type 接收人的类型
 */
function Savemsg(msgdata, is_add, is_send, accept_user_id = 0, accept_user_type = 0) {
	msgdata.forEach((value, key) => {
		/* 如下是好友的类型和id */
		var user_type = '';
		var user_id = '';
		if (is_send) {
			if (accept_user_id == 0 || accept_user_type == 0) {
				return '参数错误';
			}
			user_type = accept_user_type;
			user_id = accept_user_id;
		} else {
			user_type = value.usr_type;
			user_id = value.usr_id;
		}
		/* 如上是好友的类型和id */

		var classkey = 'class' + value.class_id; //班级聊天记录key
		var typekey = value.class_id + 'usr_type' + user_type; //好友类型key
		var userkey = value.class_id + 'usr_type' + user_type + 'user' + user_id; //好友key

		if (is_add) {
			var classdata = uni.getStorageSync(classkey);
			if (classdata) {
				classdata.num = classdata.num + 1;
				uni.setStorageSync(classkey, classdata);
			} else {
				var data = {
					num: 1
				}
				uni.setStorageSync(classkey, data);
			}

			var typedata = uni.getStorageSync(typekey);
			if (typedata) {
				typedata.num = typedata.num + 1;
				uni.setStorageSync(typekey, typedata);
			} else {
				var data = {
					num: 1
				}
				uni.setStorageSync(typekey, data);
			}
		}

		var user_data = uni.getStorageSync(userkey);
		if (user_data) {
			user_data.num = is_add ? (user_data.num + 1) : user_data.num;
			user_data.msgList.push(value);
			uni.setStorageSync(userkey, user_data);
		} else {
			var msgarr = [];
			msgarr.push(value);
			var num = is_add ? 1 : 0;
			var data = {
				num: num,
				msgList: msgarr
			}
			uni.setStorageSync(userkey, data);
		}

		// if (is_add) {
		// 	uni.getStorage({
		// 		key: classkey,
		// 		success: function(res) {
		// 			var data = res.data;
		// 			var num = data.num + 1;
		// 			uni.setStorage({
		// 				key: classkey,
		// 				data: {
		// 					num: num
		// 				}
		// 			})
		// 		},
		// 		fail: function() {
		// 			uni.setStorage({
		// 				key: classkey,
		// 				data: {
		// 					num: 1
		// 				}
		// 			})
		// 		}
		// 	})
		// 	uni.getStorage({
		// 		key: typekey,
		// 		success: function(res) {
		// 			var data = res.data;
		// 			var num = data.num + 1;
		// 			uni.setStorage({
		// 				key: typekey,
		// 				data: {
		// 					num: num
		// 				}
		// 			})
		// 		},
		// 		fail: function() {
		// 			uni.setStorage({
		// 				key: typekey,
		// 				data: {
		// 					num: 1
		// 				}
		// 			})
		// 		}
		// 	})
		// }
		// uni.getStorage({
		// 	key: userkey,
		// 	success: function(res) {
		// 		var msg = res.data;
		// 		msg.num = is_add ? (msg.num + 1) : msg.num;
		// 		uni.setStorage({
		// 			key: userkey,
		// 			data: msg
		// 		})
		// 	},
		// 	fail: function() {
		// 		var msgarr = [];
		// 		msgarr.push(value);
		// 		var num = is_add ? 1 : 0;
		// 		uni.setStorage({
		// 			key: userkey,
		// 			data: {
		// 				num: num,
		// 				msgList: msgarr
		// 			}
		// 		})
		// 	}
		// });
	})
}

function Saveuser(userinfo, content,create_time,noneNum=0,is_mutual_follow=null) {
	
	
	var chatuserlist = uni.getStorageSync('chatuserlist') ? uni.getStorageSync('chatuserlist') : {};
	var toid = JSON.stringify(Number(userinfo.user_id));

	if (!chatuserlist || !chatuserlist[toid]) {
		let data={
			user_id:userinfo.user_id,
			nicheng:userinfo.nicheng,
			avatar:userinfo.avatar,
			content:content,
			create_time:create_time,
			is_mutual_follow:is_mutual_follow,
			noneNum:noneNum
		}
		chatuserlist[toid] = data;
		uni.setStorageSync('chatuserlist', chatuserlist);
	} else {
			if(content){
			chatuserlist[toid]['content'] = content;
			}
			if(create_time){
				chatuserlist[toid]['create_time'] = create_time;
			}
			if(is_mutual_follow){
				chatuserlist[toid]['is_mutual_follow'] = is_mutual_follow;
			}
			if(noneNum>0){
				chatuserlist[toid]['noneNum'] = chatuserlist[toid]['noneNum']+noneNum;
			}	
			uni.setStorageSync('chatuserlist', chatuserlist);
	}
	
	
}

/* 
 * 格式日期格式，传入日期格式
 * @author	Asan
 */
Date.prototype.format = function(format_str, args) {
	function digit(number, length) {
		return '00000000000000000000'.replace(/0$/, number.toString()).slice(-length || -2);
	}
	var format_str = format_str || 'yyyy-MM-dd HH:mm:ss';
	return format_str
		.replace(/yyyy/g, digit(this.getFullYear(), 4))
		.replace(/MM/g, digit(this.getMonth() + 1))
		.replace(/M/g, this.getMonth() + 1)
		.replace(/dd/g, digit(this.getDate()))
		.replace(/d/g, this.getDate())
		.replace(/HH/g, digit(this.getHours()))
		.replace(/H/g, this.getHours())
		.replace(/mm/g, digit(this.getMinutes()))
		.replace(/m/g, this.getMinutes())
		.replace(/ss/g, digit(this.getSeconds()))
		.replace(/s/g, this.getSeconds())
};
/* 
 * 格式日期格式，传入多个日期,判断日期所在区间
 * @author	Asan
 */
Date.prototype.interval = function(times) {
	var _l = arguments.length;
	var _interval = new Array(_l + 2);
	while (_l--) {
		if (arguments[_l] instanceof Date) {
			_interval[_l + 1] = arguments[_l]
		} else if ('string' === typeof arguments[_l]) {
			var a = arguments[_l].split(/[^0-9]/);
			_interval[_l + 1] = a.length === 6 ? new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]) : new Date(
				arguments[_l])
		}
	}
	_l = arguments.length
	while (_l) {
		if (+this > +_interval[_l]) return _l
		_l--
	}
	return 0
};
/* 
 * 数组工具, 数组切割
 * @author	Asan
 */
Array.prototype.chunk = function(size, fill) {
	if (size >= this.length) return [this.map(x => x)]
	var n = ~~(this.length / size),
		res = [];
	do {
		res.unshift(this.slice(size * n, size * (n + 1)))
	} while (n--)
	if (fill && this.length % size) {
		res[res.length - 1] = res[res.length - 1].concat(new Array(size - this.length % size).fill(undefined))
	}
	return res
}
/* 
 * 数组工具， diff, 空间换时间, 最大时间复杂度 O(2m+n)
 * @param	arr	target Array
 * 			key	  key of Object Array	
 * @author	Asan
 * @return [[A], [B], [c]]	A: remove, B: remain, C: add
 */
Array.prototype.diff = function(arr, key, indexOnly) {
	var i = this.length,
		map = {},
		ans = [
			[],
			[],
			[]
		],
		dp = new Array(this.length),
		indexOnly = indexOnly || false,
		_key;
	while (i--) {
		_key = key ? this[i][key] : this[i]
		map[_key] = i
	}
	i = arr.length;
	while (i--) {
		_key = key ? arr[i][key] : arr[i]
		if (map[_key] !== undefined) {
			dp[i] = _key
			ans[1].push(indexOnly ? map[_key] : this[map[_key]])
			continue
		}
		ans[2].push(indexOnly ? i : arr[i]) // add
	}
	i = dp.length
	while (i--) {
		dp[i] === undefined && ans[0].push(indexOnly ? i : this[i]) // remove
	}
	return ans
}

/* 
 * 数组工具, 数组赋值
 * Array.range(5) --> [0,1,2,3,4]
 * @author	Asan
 */
Array.range = function(range, offset, start) {
	if (!range) return [];
	var offset = 'number' === typeof offset ? offset : 1,
		start = start || 0;
	if (range < 0) return Array.apply(null, Array(-range)).map((x, i) => start + (-range - i) * offset)
	return Array.apply(null, Array(range)).map((x, i) => start + i * offset)
}

function setquestion(data) {
	data.forEach((item, key) => {
		item.type_name = getTypeName(item.question_typeid);
		if (item.is_sub_question == 1) {
			switch (item.question_typeid) {
				case 1:
				case 2:
					var answer_text = '';
					item.answer_list.forEach((aitem, akey) => {
						var str = 'A';
						var code = str.charCodeAt();
						var str2 = String.fromCharCode(code + akey);
						aitem.text = str2;
						if (aitem.is_answer == 1) {
							answer_text = answer_text + str2;
						}
					});
					item.answer_text = answer_text;
					break;
				case 3:
					var answer_text = '';
					item.answer_list.forEach((aitem, akey) => {
						if (aitem.is_answer == 1) {
							answer_text = aitem.answer;
						}
					});
					item.answer_text = answer_text;
					break;
				default:
					var answer_text = [];
					item.answer_list.forEach((aitem, akey) => {
						answer_text.push(aitem.answer);
					});
					item.answer_text = answer_text.join('......');
					break;
			}
		}
	});
}

function DebounceBy(fn, t) {
	const delay = t || 500
	let timer
	return function() {
		const args = arguments
		if (timer) {
			clearTimeout(timer)
		}
		const callNow = !timer

		timer = setTimeout(() => {
			timer = null
		}, delay)

		if (callNow) fn.apply(this, args)
	}
}


module.exports = {
	formatTime: formatTime,
	formatLocation: formatLocation,
	dateUtils: dateUtils,
	apiPath: apiPath,
	Replace_str: Replace_str,
	checkUpdate: checkUpdate,
	getToken: getToken,
	Replace_img: Replace_img,
	getAnalysis: getAnalysis,
	latex_reques: latex_reques,
	latex_answer: latex_answer,
	getFormatTime: getFormatTime,
	getBriefTime: getBriefTime,
	getLeftTime: getLeftTime,
	getAllTime: getAllTime,
	getnewTime: getnewTime,
	getTodayTime: getTodayTime,
	getDES: getDES,
	Savemsg: Savemsg,
	Clearnum: Clearnum,
	setquestion: setquestion,
	getgradeName: getgradeName, //年级显示
	getStage: getStage, //年级数组显示
	getTypeName: getTypeName, //题型显示
	getKindName: getKindName, //类型显示
	getArtType: getArtType, //格式化文章类型
	getIcon: getIcon, //科目图标显示
	DebounceBy: DebounceBy,
	artHandle: artHandle, //文章数据处理
	Saveuser:Saveuser
}
